<template>
  <div class="data-results">
    <div class="table-container">
      <el-tooltip content="用户名 admin，密码 123456" placement="top">
        <el-link type="primary" href="http://localhost:8080/#/" target="_blank">跳转区块链浏览器</el-link>
      </el-tooltip>
    </div>
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">项目核算结果存证信息</span>
      </div>
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="项目ID">{{ LCAProjectResult.productId || "未知项目" }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ LCAProjectResult.productName || "未知产品" }}</el-descriptions-item>
        <el-descriptions-item label="项目开始时间">{{ LCAProjectResult.projectStart || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="项目结束时间">{{ LCAProjectResult.projectEnd || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="核算结果">{{ LCAProjectResult.aggregatedPCF || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ LCAProjectResult.aggregatedPCFUnit || "未设定" }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">项目核算结果区块链信息</span>
      </div>
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="区块编号">{{ blockchainData.blockNumber || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="区块数据哈希">{{ blockchainData.dataHash || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="上一区块哈希">{{ blockchainData.previousHash || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="交易 ID">{{ blockchainData.txId || "未获取" }}</el-descriptions-item>
      </el-descriptions>
    </div>
<!-- 
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">供应链碳数据上链列表</span>
      </div>
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="区块编号">{{ blockchainData.blockNumber || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="区块数据哈希">{{ blockchainData.dataHash || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="上一区块哈希">{{ blockchainData.previousHash || "未获取" }}</el-descriptions-item>
        <el-descriptions-item label="交易 ID">{{ blockchainData.txId || "未获取" }}</el-descriptions-item>
      </el-descriptions>
    </div> -->
  </div>
</template>

<script setup lang="ts" name="useProtable">
import { ref, onMounted, watch, nextTick } from "vue";
import { Project } from "@/api/interface";
import { useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";

const route = useRoute();
/**实际使用的项目列表 */
const fetchedProjectList = ref<Partial<Project.ResProject>[]>([]);
const baseUrl = import.meta.env.VITE_BASE_URL;
const txId = ref<string>("");

//区块链上信息
const LCAProjectResult = ref({
  projectId: "",
  userName: "",
  productId: "",
  productName: "",
  projectStart: "",
  projectEnd: "",
  aggregatedPCF: "",
  aggregatedPCFUnit: "",
  SupplychainCarbonTxIDs: ""
});
// 区块链数据
const blockchainData = ref({
  blockNumber: "",
  dataHash: "",
  previousHash: "",
  txId: ""
});

// 得到区块链上记录的项目核算结果
const getLCAProjectResult = async () => {
  try {
    const projectId = route.params.projectId?.toString();
    if (!projectId) return;
    // 调用接口获取区块链信息
    const response = await axios.get(baseUrl + `/api/carbon/queryBlockchainDocument?txId=${txId.value}`);
    console.log("response.data", response.data);
    if (response.data.code === 200) {
      const docDataStr = response.data.data[0].docData;
      let docDataObj = {};
      try {
        docDataObj = JSON.parse(docDataStr);
        console.log("转换后的对象：", docDataObj);
        LCAProjectResult.value.productId = docDataObj.projectId || "";
        LCAProjectResult.value.productName = docDataObj.productName || "";
        LCAProjectResult.value.projectStart = docDataObj.projectStart || "";
        LCAProjectResult.value.projectEnd = docDataObj.projectEnd || "";
        LCAProjectResult.value.aggregatedPCF = docDataObj.aggregatedPCF || "";
        LCAProjectResult.value.aggregatedPCFUnit = docDataObj.aggregatedPCFUnit || "";
      } catch (e) {
        console.error("docData 解析失败：", e);
      }
    } else {
      console.error("获取区块链信息失败:", response.data.message);
    }
  } catch (error) {
    console.error("调用区块链查询接口出错:", error);
  }
};

// 获取区块链存证信息
const getBlockchainInfo = async () => {
  try {
    const projectId = route.params.projectId?.toString();
    if (!projectId) return;
    const response = await axios.get(baseUrl + `/api/carbon/queryBlockByTxID`, {
      params: {
        txId: txId.value
      }
    });
    console.log("getBlockchainInfo", response.data);
    if (response.data.code === 200) {
      blockchainData.value = response.data.data;
      console.log("区块链信息获取成功:", blockchainData.value);
    } else {
      console.error("获取区块链信息失败:", response.data.message);
    }
  } catch (error) {
    console.error("调用区块链查询接口出错:", error);
  }
};

// 挂载函数
onMounted(async () => {
  // 初始化项目
  console.log("开始初始化项目");
  await initProjectList();
  await nextTick();
  await getTxId();
  await nextTick();
  await getBlockchainInfo(); // 获取区块链信息
  await nextTick();
  await getLCAProjectResult();
  await nextTick();
  console.log("初始化项目结束");
});

const initProjectList = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getProjectList", {
      userId: userId
    });
    if (response.data && response.data.code === 200) {
      fetchedProjectList.value = response.data.data;
      console.log("响应数据_读取项目列表:", fetchedProjectList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取项目列表失败";
      console.error("获取项目列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取项目列表出错:", error);
    ElMessage.error("获取项目列表失败，可能是因为参数错误或网络问题");
  }
};

const getTxId = async () => {
  const projectId = route.params.projectId?.toString();
  if (!projectId) return;
  try {
    const response = await axios.get(`${baseUrl}/api/carbon/getTxId?projectId=${projectId}`);
    if (response.data && response.data.code === 200) {
      txId.value = response.data.data.txId;
      console.log("获取到的txId:", txId.value);
    } else {
      console.warn("获取txId失败：", response.data?.msg || "未知错误");
    }
  } catch (error) {
    console.error("请求txId出错：", error);
  }
};

// 监听 fetchedProjectList 的变化并更新图表
watch(
  () => fetchedProjectList.value,
  newVal => {
    if (newVal.length > 0) {
    }
  },
  { immediate: true }
);

// 监听路由参数变化
watch(
  () => route.params.projectId,
  async () => {
    await getBlockchainInfo(); // 当项目ID变化时重新获取区块链信息
  }
);
</script>
<style>
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.echarts {
  width: 100%;
  height: 400px;
}
.custom-descriptions .el-descriptions__label {
  width: 150px !important;
  font-weight: 500;
}
.custom-descriptions .el-descriptions__content {
  word-break: break-all;
}
</style>
